package com.dq.controller.org;

import com.dq.context.Constant;
import com.dq.exception.customException.AdminException;
import com.dq.vo.Vo;

import com.dq.domain.org.Org;
import com.dq.domain.position.OrgPosition;
import com.dq.domain.org.centre.OrgDeptPositionCentre;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cf
 */
@Api(description = "门店岗位关联")
@RestController
@RequestMapping("sys/org/orgDeptPosition/")
public class OrgDeptPositionController extends AllService {

    @ApiOperation("门店关联岗位")
    @PostMapping("/relation/{orgId}")
    @RequiresPermissions("sys:orgDeptPosition:relation")
    public Vo relationPositionAndDept(@RequestBody() List<Long> orgPositionIds, @PathVariable @ApiParam(value = "门店id") Long orgId) throws AdminException {
        SysUser user = sysUserService.getUser();

        Org org = dao.get(Org.class, orgId);
        if (org == null) {
            throw new AdminException("无对应门店");
        }
        List<OrgDeptPositionCentre> list = orgDeptPositionRepository.findByDeletedAndOrgOrderByIdDesc(false, org);
        if (list != null && list.size() > 0) {
            orgDeptPositionRepository.deleteAll(list);
        }
        if (orgPositionIds.isEmpty()) {
            return new Vo(HttpStatus.OK);
        }
        list = new ArrayList<>();
        List<OrgPosition> orgPositionList = orgPositionRepository.findByIdIn(orgPositionIds);
        for (OrgPosition position : orgPositionList) {
            OrgDeptPositionCentre orgDeptPositionCentre = new OrgDeptPositionCentre();
            orgDeptPositionCentre.setOrg(org);
            orgDeptPositionCentre.setOrgPosition(position);

            saveBaseOrgDeptPositionCentre(user, orgDeptPositionCentre);

            list.add(orgDeptPositionCentre);
        }
        orgDeptPositionRepository.saveAll(list);

        return new Vo(HttpStatus.OK);
    }

    /**
     * 岗位服务关联 基本属性设置
     */
    public void saveBaseOrgDeptPositionCentre(SysUser user, OrgDeptPositionCentre orgDeptPositionCentre) {
        orgDeptPositionCentre.setVersion(Constant.VERSION_VALUE);
        orgDeptPositionCentre.setDeleted(false);
        orgDeptPositionCentre.setCreateTime(System.currentTimeMillis());
        orgDeptPositionCentre.setLastModifyTime(System.currentTimeMillis());
        orgDeptPositionCentre.setCreateUser(user);
        orgDeptPositionCentre.setUpdateUser(user);
    }

}
